package com.example.wendao.view.ui.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.core.app.ShareCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.ImgUtils;
import com.example.wendao.databinding.FragmentNewsDetailBinding;
import com.example.wendao.model.entity.News;
import com.example.wendao.model.entity.NewsPics;
import com.example.wendao.model.entity.User;
import com.example.wendao.viewmodel.NewsViewModel;
import com.example.wendao.viewmodel.UserViewModel;

public class NewsDetailFragment extends Fragment {

    private FragmentNewsDetailBinding newsDetailBinding;
    private News news = null;
    private User user = null;
    private UserViewModel userViewModel;
    private NewsViewModel newsViewModel;
    int coin_num=9;
    private Bundle bundle;

    public NewsDetailFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        newsDetailBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_news_detail, container, false);
        View view = newsDetailBinding.getRoot();
        int NewsIds = 0;
        int userId = 0;
        bundle = getArguments();
        if (bundle != null){
            NewsIds = bundle.getInt("newId");
            userId = bundle.getInt("userId");
        }
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        newsViewModel = new ViewModelProvider(App.getInstance()).get(NewsViewModel.class);

        // 获取作者
        User author = userViewModel.getUserById(userId);


        user=userViewModel.getCurrentUser();
        if (user!=null) {
           coin_num = user.getCoins();
        }
        //点击事件需要传值
        news = newsViewModel.getNewsById(NewsIds);
        if (news != null){

            if (userViewModel.userLoggedIn()){
                // 如果已经点过赞，禁用按钮
                if (userViewModel.newsIsAgree(news.getNewsId())){
                    newsDetailBinding.agreeButton.setEnabled(false);
                }
                if (userViewModel.isFollowed(author)){
                    newsDetailBinding.btnFollow.setEnabled(false);
                }
            }

            //新闻内容
            String news_content = news.getNewsContent();
            newsDetailBinding.plantDescription.setText(news_content);
            //新闻标题
            String Title = news.getNewsTitle();
            newsDetailBinding.plantDetailNewsTitle.setText(Title);
            //新闻时间
            String Time = news.getNewsTime();
            newsDetailBinding.plantNewTime.setText(Time);
            NewsPics newsPics = newsViewModel.getCoverByNewId(news.getNewsId());
            if (newsPics != null) {
                byte[] bytes = newsPics.getNewsPic();
                newsDetailBinding.newsDetailImage.setImageBitmap(ImgUtils.barrayToBitmap(bytes));
            }
            newsDetailBinding.tvUsername.setText(author.getUsername());
        }

        newsDetailBinding.agreeButton.setOnClickListener(v -> {

            if (!userViewModel.userLoggedIn()){
                Toast.makeText(getContext(), "请登录后操作", Toast.LENGTH_SHORT).show();
            } else {

                Toast.makeText(getContext(),"已点赞",Toast.LENGTH_SHORT).show();
                newsDetailBinding.agreeButton.setEnabled(false);

                news.setNewsAgree(news.getNewsAgree() + 1);
                User user = userViewModel.getCurrentUser();
                user.setAnewsId(userViewModel.getCurrentUser().getAnewsId() + "," + news.getNewsId());
                userViewModel.setCurrentUser(user);
                userViewModel.updateUser(user);
                newsViewModel.updateSomeNews(news);
            }

        });

        newsDetailBinding.btnFollow.setOnClickListener(v -> {
            if (!userViewModel.userLoggedIn()){
                Toast.makeText(getContext(), "请登录后操作", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(),"已关注",Toast.LENGTH_SHORT).show();
                newsDetailBinding.btnFollow.setEnabled(false);
                userViewModel.follow(author);
            }
        });

        newsDetailBinding.toolbar.setNavigationOnClickListener(v -> {
            Navigation.findNavController(v).navigateUp();
        });
        newsDetailBinding.toolbar.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.action_share) {
                createShareIntent();
                return true;
            }
            return false;
        });

//
//        //点赞插件
//        final GoodView goodView = new GoodView(view.getContext());
//        Button button = new Button(view.getContext());
//        button.setOnClickListener(v -> {
//            goodView.setText("+1");
//            goodView.show(v);
//        });
//        newsDetailBinding.toolbar.setNavigationOnClickListener(v -> {
//            Navigation.findNavController(v).navigateUp();
//        });
//
//        newsDetailBinding.toolbar.setOnMenuItemClickListener(item -> {
//            if (item.getItemId() == R.id.action_share) {
//                createShareIntent();
//                return true;
//            }
//            return false;
//        });
//        newsDetailBinding.agreeButton.setOnClickListener(view1 -> {
//            Toast.makeText(view1.getContext(),"已点赞",Toast.LENGTH_SHORT).show();
//            newsDetailBinding.agreeButton.setEnabled(false);
//            Date now = new Date();
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
//            String time = dateFormat.format( now );
//            user.setBnewsId(time+"点赞了科技新闻");
//        });
//        newsDetailBinding.collectButton.setOnClickListener(view12 -> {
//            Toast.makeText(view12.getContext(),"已收藏",Toast.LENGTH_SHORT).show();
//            newsDetailBinding.collectButton.setText("取消收藏");
//            Date now = new Date();
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
//            String time = dateFormat.format( now );
//            user.setAnewsId(time+"收藏了科技新闻");
//        });
//        newsDetailBinding.giveCionButton.setOnClickListener(view13 -> Toast.makeText(view13.getContext(),"感谢您的贡献，目前您的金币数"+coin_num,Toast.LENGTH_SHORT).show());
        return view;
    }

    private void createShareIntent(){
        String shareText = "分享文本";
        Intent shareIntent = ShareCompat.IntentBuilder.from(getActivity())
                .setText(shareText)
                .setType("text/plain")
                .createChooserIntent()
                .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        startActivity(shareIntent);
    }
}

